const app = getApp();
const qiniuUploader = require("../../../utils/qiniuUploader-min.js");
import grace from "../../../utils/grace.js";

grace.page({
  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    students: [],
    tmpImagePath: '' // 用户选择的图片路径
  },
  onLoad() {
    let that = this;

    that.initQiniu();
  },
  onShow() {
    let that = this;
    let token = wx.getStorageSync('token');
    if(!token){
      wx.navigateTo({
        url: '/pages/common/authorize/index'
      })
      return;
    }
    let school_id = wx.getStorageSync('school_id')

    wx.showLoading({
      title: '加载中...',
    })
    let url = app.globalData.api + '/api/v1.0/banners/' + school_id + '/guardian_index';
    that.$http.get(url).then((res) => {
      if (res.data.code == 0) {
        that.$data.banners = res.data.data;
      }
    }).catch(err => {
      console.log(err.status, err.message);
    })

    url = app.globalData.api + '/api/v1.0/guardian/students/' + school_id + '/' + wx.getStorageSync('partner_id');
    that.$http.get(url, {token: token}).then((res) => {
      if (res.data.code == 0) {
        that.$data.students = res.data.data;
      }
      wx.hideLoading();
    }).catch(err => {
      console.log(err.status, err.message);
    })
  },
  previewImage(e) {
    if(e.currentTarget.dataset.url){
      let urls = [e.currentTarget.dataset.url];
      wx.previewImage({
        urls: urls
      })
    }
  },
  attendance(e) {
    wx.navigateTo({
      url: "/pages/home/guardian/attendance?student_id=" + e.currentTarget.dataset.id
    })
  },
  remove(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '加载中...',
    })
    let url = app.globalData.api + '/api/v1.0/removeChild';
    that.$http.put(url, {
      token: token,
      student_id: e.currentTarget.dataset.id,
      partner_id: wx.getStorageSync('partner_id')
    }).then((res) => {
      if (res.data.code == 0) {
        that.$data.students.forEach(function(item, index, arr) {
          if(item['id'] == e.currentTarget.dataset.id) {
            arr.splice(index, 1);
          }
        });
      }
      wx.hideLoading();
    }).catch(err => {
      console.log(err.status, err.message);
    })
  },
  // 初始化七牛相关参数
  initQiniu() {
    let options = {
      uploadURL: 'https://up-z2.qbox.me',
      uptokenURL: app.globalData.api + '/api/v1.0/qiniuUptoken',
      domain: 'https://img.houdeyun.com/' // domain 为七牛空间（bucket)对应的域名
    };
    qiniuUploader.init(options);
  },
  didPressChooesImage(e) {
    let that = this;
    let token = wx.getStorageSync('token');
    // 微信 API 选文件
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(photo) {
        let tempFilesSize = photo.tempFiles[0].size;
        if(tempFilesSize <= 2000000){
          that.$data.tmpImagePath = photo.tempFilePaths[0];

          // 交给七牛上传
          new Promise(function(resolve, reject) {
            qiniuUploader.upload(that.$data.tmpImagePath, (res) => {
              resolve(res.imageURL);
            }, (error) => {
              reject('error');
              console.error('error: ' + JSON.stringify(error));
            });
          }).then(function(imageUrl) {
            // 更新孩子照片
            let url = app.globalData.api + '/api/v1.0/childPic/' + e.currentTarget.dataset.id;
            let params = {
              token: token,
              pic_url: imageUrl
            }
            that.$http.put(url, params).then((res) => {
              if (res.data.code == 0) {
                // 更新孩子头像
                for (let i = 0; i < that.$data.students.length; i++) {
                  if (that.$data.students[i].id == e.currentTarget.dataset.id) {
                    that.$data.students[i].pic_url = imageUrl;
                  }
                }
              } else {
                wx.showModal({
                  title: '错误',
                  content: res.data.msg,
                  showCancel: false
                })
              }
              wx.hideLoading();
            }).catch(err => {
              console.log(err.status, err.message);
            })
          })
        }else{
          wx.showToast({
            title:'上传图片不能大于2M!',  //标题
            icon:'none'       //图标
          })
        }
      }
    })
  }
})